from flask import render_template, request, flash, redirect, url_for, abort
from flask_login import current_user
from app.model.order import Order
from app.model.product import Product
from app.web import web


@web.route('/product/list', methods=['GET'])
def product_list_ep():
    """
        普通用户的商品列表路由

    :arg:
        k: 搜索关键词，可空
        p: 页码，可空，默认第1页
    """

    if current_user.is_authenticated and current_user.admin:
        return redirect(url_for('admin.index_ep'))
    key = request.args.get('k', '', str)
    page = request.args.get('p', 1, int)
    pagination = Product.query.filter(Product.valid == 1,
                                      Product.reserve > 0,
                                      Product.name.like('%' + key + '%')
                                      ).order_by(Product.create_time.desc()).paginate(page, per_page=8)
    products = pagination.items
    return render_template('web/product/list.html',
                           products=products,
                           pagination=pagination)


@web.route('/product/<product_id>', methods=['get'])
def product_item_ep(product_id):
    """
        普通用户的商品详情路由

    :param:
        product_id: 商品id

    :returns:
        product: 商品实例对象
        close_count: 与该商品相关的订单数
        sales: 销售量，该商品售出的总件数
    """
    pd = Product.query.filter_by(id=product_id).first()
    if not pd:
        abort(404)
    orders = Order.query.filter_by(product_id=pd.id).all()
    sales = 0
    for order in orders:
        sales = sales + order.count
    flash({}, 'form')
    return render_template('web/product/detail.html', product=pd, close_count=len(orders), sales=sales)
